package com.metaverse.backend.domain;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.metaverse.backend.dto.MenuDTO;
import com.metaverse.backend.security.Authority;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Where(clause = "active = 1")
@ApiModel("菜单")
public class Menu extends BaseEntity implements Serializable {

    @ApiModelProperty("菜单名称")
    private String name;

    @ApiModelProperty("路径")
    private String path;

    @ApiModelProperty("图标")
    private String icon;

    @ApiModelProperty("排序")
    private Integer sort;

    @ApiModelProperty("父级菜单")
    private Long parent;

    @ApiModelProperty("是否根")
    private Boolean root;

    @ApiModelProperty("是否启用")
    private Boolean enabled;

    @ApiModelProperty("是否激活")
    private Boolean active;

    @ApiModelProperty("分类")
    private String category;

    @OneToMany
    @JoinColumn(name = "parent", insertable = false, updatable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    List<Menu> children;

    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH})
    @JoinTable(
            name = "menu_authority",
            joinColumns = {@JoinColumn(name = "menu_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "authority", referencedColumnName = "name")})
    @ExcelIgnore
    private Set<Authority> authorities = new HashSet<>();

    public static Menu from(MenuDTO menuDTO) {
        Menu menu = Menu.builder()
                .name(menuDTO.getName())
                .path(menuDTO.getPath())
                .icon(menuDTO.getIcon())
                .sort(menuDTO.getSort())
                .parent(menuDTO.getParent())
                .root(menuDTO.getRoot())
                .enabled(menuDTO.getEnabled())
                .active(menuDTO.getActive())
                .category(menuDTO.getCategory())
                .children(null)
                .build();
        menu.setId(menuDTO.getId());
        return menu;
    }
}
